package cn.atcoder.air.config;

import cn.atcoder.air.transport.ServerTransport;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yangjunda1
 * @description
 * @date 5/10/19 3:24 PM
 */
public class ProviderConfig<T> extends AbstractInterfaceConfig<T> {

    private transient T ref;

    private ServerTransport server;

    private Map<String, Method> methods = new ConcurrentHashMap<>();

    protected transient volatile boolean exported;

    public synchronized void export() {
        if (this.exported) {
            return;
        }
        if (this.ref == null) {
            throw new NullPointerException("ref is null");
        }
        Method[] methods = ref.getClass().getMethods();
        for (Method method : methods) {
            this.methods.put(method.getName(), method);
        }
        ProviderFactory.cacheProviderConfig(this);

    }

    public T getRef() {
        return ref;
    }

    public void setRef(T ref) {
        this.ref = ref;
    }

    public ServerTransport getServer() {
        return server;
    }

    public void setServer(ServerTransport server) {
        this.server = server;
    }

    public Method getMethod(String methodName) {
        return methods.get(methodName);
    }

    public T refer() {
        return clazz.cast(this.ref);
    }
}
